// import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, DatePicker, Radio, Input, Select } from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { queryoversaleTable, downloadExcel, queryCityInfo } from './service';
import moment from 'moment';
import styles from './index.less';
import { formatFlightNo, controlTableHeight } from '@/utils/pagesGeneralMethods'; // 页面通用方法

const { Option } = Select;

// 临时假数据
let tempArr = [];

let selectData = [
  {
    CITY3CODE: 'CTU',
    CITYNAME: '成都'
  },{
    CITY3CODE: 'SHA',
    CITYNAME: '上海虹桥'
  },{
    CITY3CODE: 'PEK',
    CITYNAME: '北京'
  }]
// let hiddenData = null;
const VipOversale = props => {
  const {
    location: { state },
  } = props;
  const { data: selectData } = useRequest(queryCityInfo);
  const [exportFlag, handleExportFlag] = useState(''); // 导出标志
  const [isCollapse, controlC] = useState(true); //搜索面板是否折叠

  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();

  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);


  const columns = [
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 100,
      order: 15
    },
    {
      title: '旅客类型',
      key: 'type',
      dataIndex: 'type',
      width: 100,
      hideInSearch: true,
      filters: [
        { text: '金卡', value: '0' },
        { text: '银卡', value: '1' },
      ],
      valueEnum: {
        '': '全部',
        '0': '金卡',
        '1': '银卡',
      },
    },
    {
      title: '高端旅客类型',
      dataIndex: 'higntype',
      hideInTable: true,
      order: 14,
      filters: [
        { text: '金卡', value: '0' },
        { text: '银卡', value: '1' },
      ],
      valueEnum: {
        '': '全部',
        '0': '金卡',
        '1': '银卡',
      },
    },
    {
      title: 'PNR',
      dataIndex: 'PNR',
      order: 8,
      width: 100,
    },
    {
      title: '票号',
      key: 'ticketNo',
      order: 7,
      dataIndex: 'ticketNo',
      initialValue: '',
      width: 120,
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      key: 'flightNo',
      width: 100,
      hideInSearch: true,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return (
          <Input
            {...rest}
            onChange={e => {
              e.target.value = formatFlightNo(e.target.value);
              rest.onChange(e.target.value);
            }}
            maxLength={6}
            placeholder="3U"
          />
        );
      },
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      order: 6,
      width: 100,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return <DatePicker style={{ width: '100%' }} format={format} {...rest} />;
      },
    },
    {
      title: '航段',
      dataIndex: 'segment',
      width: 120,
      hideInSearch: true,
    },
    {
      // 多个查询选项
      title: '出发航站',
      dataIndex: 'sta',
      width: 100,
      order: 5,
      hideInTable:true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '到达航站',
      dataIndex: 'std',
      width: 100,
      order: 4,
      hideInTable:true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '原PNR',
      dataIndex: 'oldPNR',
      width: 100,
      order: 13
    },
    {
      title: '原票号',
      dataIndex: 'oldTicketNo',
      width: 120,
      order: 12,
    },
    {
      title: '原航班号',
      dataIndex: 'oldflightNo',
      key: 'oldflightNo',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '原航班日期',
      dataIndex: 'oldflightDate',
      width: 100,
      order: 11,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return <DatePicker style={{ width: '100%' }} format={format} {...rest} />;
      },
    },
    {
      // 多个查询选项
      title: '原出发航站',
      dataIndex: 'oldSta',
      width: 100,
      order: 10,
      hideInTable:true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '原到达航站',
      dataIndex: 'oldStd',
      width: 100,
      order: 9,
      hideInTable:true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '原航段',
      dataIndex: 'oldsegment',
      width: 120,
      hideInSearch: true
    },
    {
      title: '操作时间',
      dataIndex: 'opTime',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '操作员工号',
      dataIndex: 'opNum',
      width: 120,
      order: 3,
    },
    {
      title: '操作起始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 2,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return <DatePicker style={{ width: '100%' }} format={format} {...rest} />;
      },
    },
    {
      title: '操作结束日期',
      hideInTable: true,
      dataIndex: 'endDate',
      order: 1,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return <DatePicker style={{ width: '100%' }} format={format} {...rest} />;
      },
    },
  ];

  const [inited, setInited] = useState(false);
  useEffect(() => {
    if (actionRef.current && inited) {
      reloadTable();
    } else {
      setInited(true);
    }
  }, [inited]);

  // 切换清空搜索
  // useEffect(() => {
  //   hiddenData = null;
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, []);

  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {
    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      return { ...params };
    } else {
      if (
        event &&
        event.target &&
        event.target.querySelector &&
        event.target.querySelector('span') &&
        event.target.querySelector('span').innerText === '查 询'
      ) {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = '';
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = '';
        }
      } else if (
        event &&
        event.target &&
        event.target.querySelector &&
        event.target.querySelector('span') &&
        event.target.querySelector('span').innerText === '重 置'
      ) {
        ref.current.setFieldsValue({
          startDate: moment(),
          endDate: moment(),
        });
        // hiddenData = {};
      }
      // return { ...hiddenData, ...params };
      return { ...params };
    }
  }, []);

  const [searchParams, handleSearchParams] = useState(); // 存储搜索条件
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys);
    handleSelectedRows(selectedRows);
  };

  //导出方法
  const handleExport = () => {
    if (!exportFlag) {
      message.error('表格数据为空');
      return false;
    }
    const hide = message.loading('正在导出');
    let res = downloadExcel(searchParams)
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time = moment(Date.now()).format('YYYY-MM-DD HH_ss_mm');
        elink.download = '改签列表' + time + '.xls';
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <>
      <ProTable
        headerTitle={
          <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>改签列表</span>
        }
        options={{ density: false, fullScreen: true, reload:false, setting: true }}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        scroll={{ x: 1100, y: controlTableHeight(isCollapse, 360, 470) }}
        size="small"
        className={styles.vipPaxChange}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          },
          onCollapse: val => {
            controlC(val);
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     startDate: hiddenData.startDate,
            //     endDate: hiddenData.endDate,
            //     flightNo: hiddenData.flightNo,
            //     type: hiddenData.type,
            //     receiveStatus: hiddenData.receiveStatus,
            //     payType: hiddenData.payType,
            //     keySearch: hiddenData.keySearch,
            //     serviceCity: hiddenData.serviceCity,
            //   });
            // } else {
            //   hiddenData = ref.current.getFieldsValue();
            // }
          },
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={handleExport} 
          // selectedKeys={[]}
          >
            导出
          </Button>
        ]}
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['startDate'] && !params['endState']) {
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment(),
              endDate: moment(),
            });
          }
          if (!params['flightNo']) {
            ref.current.setFieldsValue({
              flightNo: '',
            });
          }
          handleSearchParams(params);
          return Promise.resolve({
            data: tempArr,
            success: true,
          })
          // return queryoversaleTable(params);
        }}
        postData={data => {
          // if (data.length === 0) {
          //   handleExportFlag(false);
          // } else {
          //   handleExportFlag(true);
          // }
          // return data;
          return data || tempArr;
        }}
        columns={columns}
        // rowSelection={AuthComponent.getAuth('overSale.index.export') ? rowSelection : false}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`,
        }}
      />
    </>
  );
};

export default Form.create()(VipOversale);
